package cn.kgc.springmvc03.handler;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/8
 * @Description: 全局异常处理类
 */
//@ControllerAdvice   //  标识该类为全局异常处理类
//@ResponseBody
@RestControllerAdvice   // @ControllerAdvice  + @ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public Map arithmeticExceptionHandler(ArithmeticException e){
        //打印异常信息
        e.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",500);
        map.put("msg","数学运算异常");
        return map;
    }

    //NullPointerException
    @ExceptionHandler(NullPointerException.class)
    public Map  nullPointerExceptionHandler(NullPointerException e){
        e.printStackTrace();
        //打印异常信息
        e.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",500);
        map.put("msg","空指针异常");
        return map;
    }


    @ExceptionHandler(Exception.class)
    public Map  exceptionHandler(Exception e){
        e.printStackTrace();
        //打印异常信息
        e.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",500);
        map.put("msg",e.getMessage());
        return map;
    }
}
